using System;
using System.Collections.Generic;
using System.Linq;
using MonoMac.Foundation;
using MonoMac.AppKit;
using VideoFlowTagger;

namespace VideoFlowTaggerMacGUI
{
	public partial class MainWindowController : MonoMac.AppKit.NSWindowController
	{
		#region Constructors
		
		private List<String> listContentAdvisory = new List<string> { "Clean", "Explicit" };
        private List<String> listMediaKind = new List<string> {
            "Movie", "Normal", "Audiobook", "Whacked Bookmark", 
            "Music Video", "Short Flim", "TV Show", "Booklet" };
		private VideoDataSource videoFiles;
		private VideoDataSourceDelegate imagesDelegate;
		private NSOpenPanel openDialog;
		private VideoFile selectedVideo;
		
		// Called when created from unmanaged code
		public MainWindowController (IntPtr handle) : base(handle)
		{
			Initialize ();
		}

		// Called when created directly from a XIB file
		[Export("initWithCoder:")]
		public MainWindowController (NSCoder coder) : base(coder)
		{
			Initialize ();
		}

		// Call to load from the XIB/NIB file
		public MainWindowController () : base("MainWindow")
		{
			Initialize ();
		}
		
		public override void Close ()
		{
			base.LoadWindow();
		}

		// Shared initialization code
		void Initialize ()
		{
			videoFiles = new VideoDataSource();
			imagesDelegate = new VideoDataSourceDelegate();
			imagesDelegate.VideoChanged += HandleImagesDelegateVideoChanged;
			
			openDialog = new NSOpenPanel();
			openDialog.CanChooseFiles = true;
			openDialog.CanChooseDirectories = false;
			openDialog.AllowsMultipleSelection = false;
			openDialog.AllowedFileTypes = new string[] { "mp4", "m4v" };
			openDialog.AllowsOtherFileTypes = false;
		}

		public void HandleImagesDelegateVideoChanged (object sender, VideoChangedEventArgs e)
		{
			Read(e.File);
			selectedVideo = e.File;
		}
		
		public override void WindowDidLoad ()
		{
			tbQueue.DataSource = videoFiles;
			tbQueue.Delegate = imagesDelegate;
			
			popRating.RemoveAllItems();
			popMediaKind.RemoveAllItems();
			popContentAdvisory.RemoveAllItems();
			
			popContentAdvisory.AddItems(listContentAdvisory.ToArray());
			popMediaKind.AddItems(listMediaKind.ToArray());
			
			txtvDescription.Font = NSFont.FromFontName("Lucida Grande", 13);
			
			Window.MakeKeyAndOrderFront(Window);
		}

		#endregion

		//strongly typed window accessor
		public new MainWindow Window {
			get { return (MainWindow)base.Window; }
		}
		
		partial void removeVideo(NSButton sender)
		{
			if (selectedVideo != null)
			{
				int index = videoFiles.IndexOf(selectedVideo);
				if ((index - 1) >= 0)
					index = index - 1;
				
				videoFiles.RemoveVideoFile(selectedVideo);
				tbQueue.ReloadData();
				
				// if the queue is not empty
				if (videoFiles.numberOfRowsInTableView(tbQueue) > 0)
				{
					tbQueue.SelectRows(new NSIndexSet((uint)index), false);
					Read(videoFiles.GetVideoFile(index));
					selectedVideo = videoFiles.GetVideoFile(index);
				}
				else
				{
					Clear();
					selectedVideo = null;
				}
			}
		}
		
		partial void addVideo(NSButton sender)
		{			
			openDialog.RunModal();
			
			// TODO: handle event of not mp4, m4v files
			if (openDialog.URL.IsFileUrl)
			{
				VideoFile videoFile = new VideoFile(openDialog.URL.Path, new iTunesMetadata());
	            videoFile.Read();
				
				videoFiles.AddVideoFile(videoFile);
				tbQueue.ReloadData();
				
				int index = videoFiles.IndexOf(videoFile);
				tbQueue.SelectRows(new NSIndexSet((uint)index), false);
				Read(videoFile);
				selectedVideo = videoFile;
			}
		}
		
		private void Clear()
		{
			lblTitle.StringValue = "";
			txtArtist.StringValue = "";
			txtAlbumArtist.StringValue = "";
			txtAlbum.StringValue = "";
			txtGenre.StringValue = "";
			popMediaKind.SelectItem(-1);
			txtTrackNum.StringValue = "";
			txtTrackTotal.StringValue = "";
			txtDiskNum.StringValue = "";
			txtDiskTotal.StringValue = "";
			txtTVShow.StringValue = "";
			txtTVEpisodeNum.StringValue = "";
			txtTVEpisodeID.StringValue = "";
			txtTVSeason.StringValue = "";
			txtTVNetwork.StringValue = "";
			txtvDescription.Value = "";
			txtCast.StringValue = "";
			txtDirectors.StringValue = "";
			txtProducers.StringValue = "";
			txtScreenwriters.StringValue = "";
			txtCopyright.StringValue = "";
			txtEncodingTool.StringValue = "";
			imgArtwork.Image = new NSImage();
		}
		
		private void Read(VideoFile videoFile)
		{
			iTunesMetadata meta = videoFile.GetiTunesMetadata();
			
			// Set title
			if (meta.Title != null)
            	lblTitle.StringValue = meta.Title;

            // Set Artist
			if (meta.Artist != null)
            	txtArtist.StringValue = meta.Artist;

            // Set Album Artist
			if (meta.AlbumArtist != null)
            	txtAlbumArtist.StringValue = meta.AlbumArtist;

            // Set Album
			if (meta.Album != null)
            	txtAlbum.StringValue = meta.Album;

            // Set Genre
			if (meta.CustomGenre != null)
            	txtGenre.StringValue = meta.CustomGenre;

            // Set Release Date
            //dpReleaseDate.SelectedDate = DateTime.Parse(meta.ReleaseDate.ToString());

            // Set Rating, ContentAdvisory, MediaKind
			if (meta.Type != null)
			{
	            String mediaKindValue = meta.Type.Value.GetStringValue();
	            int mediaKindIndex = listMediaKind.IndexOf(mediaKindValue);
				popMediaKind.SelectItem(mediaKindIndex);
			}
			if (meta.Advisory != null)
			{
				int advisoryIndex = listContentAdvisory.IndexOf(meta.Advisory);
				if (advisoryIndex != -1)
					popContentAdvisory.SelectItem(advisoryIndex);
			}

            // Set Track number and total
			if (meta.Tracknum != null)
			{
	            txtTrackNum.StringValue = meta.Tracknum.Value.GetNumber().ToString();
	            txtTrackTotal.StringValue = meta.Tracknum.Value.GetTotal().ToString();
			}

            // Set Disk number and total
			if (meta.Disk != null)
			{
	            txtDiskNum.StringValue = meta.Disk.Value.GetNumber().ToString();
	            txtDiskTotal.StringValue = meta.Disk.Value.GetTotal().ToString();
			}

            // Set TV Show, episode number, episode id, season and network
			if (meta.TVShowName != null)
            	txtTVShow.StringValue = meta.TVShowName;
            if (meta.TVEpisodeNum != null)
				txtTVEpisodeNum.StringValue = meta.TVEpisodeNum.ToString();
			if (meta.TVEpisodeId != null)
            	txtTVEpisodeID.StringValue = meta.TVEpisodeId.ToString();
			if (meta.TVSeasonNum != null)
            	txtTVSeason.StringValue = meta.TVSeasonNum.ToString();
			if (meta.TVNetwork != null)
            	txtTVNetwork.StringValue = meta.TVNetwork;
	
            // Set Description
			if (meta.Description != null)
            	txtvDescription.Value = meta.Description;

            // Set Cast, Directors, Producers, Screenwriters
			if (meta.Cast != null)
            	txtCast.StringValue = meta.Cast.Value.GetPersons();
			if (meta.Directors != null)
            	txtDirectors.StringValue = meta.Directors.Value.GetPersons();
            if (meta.Producers != null)
				txtProducers.StringValue = meta.Producers.Value.GetPersons();
			if (meta.Screenwriters!= null)
            	txtScreenwriters.StringValue = meta.Screenwriters.Value.GetPersons();

            // Set HD Video and Gapless
			
			if (meta.HDVideo != null)
				chbHDVideo.State = Convert.ToInt16(meta.HDVideo.Value);
			if (meta.Gapless != null)
            	chbGapless.State = Convert.ToInt16(meta.Gapless.Value);
			
            // Set Copyright and Encoding Tool
			if (meta.Copyright != null)
            	txtCopyright.StringValue = meta.Copyright;
			if (meta.EncodingTool != null)
            	txtEncodingTool.StringValue = meta.EncodingTool;

            // Set image
			if (!String.IsNullOrEmpty(videoFile.GetArtworkPath()))
            	imgArtwork.Image = new NSImage(videoFile.GetArtworkPath());
		}
	}
}

